package com.zeus.dubbo.filter;

import com.alibaba.dubbo.common.Constants;
import com.alibaba.dubbo.common.extension.Activate;
import com.alibaba.dubbo.rpc.*;
import com.hengxinyongli.zeus.common.constant.TrackConstant;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;

/**
 * 消费者 提供
 * 跟踪的id 跟踪的id
 * callfrom 调用方
 * callip 调用方ip
 * calltime 调用时间
 */
@Activate(group = {Constants.CONSUMER}, value = "dubboConsumerFilter")
public class DubboConsumerFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(getClass());

    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        long beginTime = System.currentTimeMillis();
        //调用者ip
        String ip = RpcContext.getContext().getAttachment(TrackConstant.CALL_IP_KEY);
        //调用应用标识
        String callFrom = RpcContext.getContext().getAttachment(TrackConstant.CALL_FROM_KEY);
        //track id
        String trackId = RpcContext.getContext().getAttachment(TrackConstant.TRACK_ID_KEY);
        if (logger.isDebugEnabled()) {
            logger.debug("srcIp {} ,callFrom {} ,trackId {} ,call time {}", ip, callFrom, trackId, System.currentTimeMillis());
        }
        RpcContext.getContext().setAttachment(TrackConstant.CALL_FROM_KEY, MDC.get(TrackConstant.CALL_FROM_KEY));
        RpcContext.getContext().setAttachment(TrackConstant.CALL_IP_KEY, MDC.get(TrackConstant.CALL_IP_KEY));
        RpcContext.getContext().setAttachment(TrackConstant.TRACK_ID_KEY, MDC.get(TrackConstant.TRACK_ID_KEY));
        Result invoke = invoker.invoke(invocation);
        long endTime = System.currentTimeMillis();
        if (logger.isDebugEnabled()) {
            logger.debug("call remote time {} ms", endTime - beginTime);
        }
        RpcContext.getContext().clearAttachments();
        return invoke;
    }
}
